/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import entity.Prodotto;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author erola
 */
public class ListaRegali extends HttpServlet {

    /**
     * Servlet utilizzata per la visualizzazione dei regali/desideri, tramite web service,
     * di un certo utente iscritto su WishListerSupport
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException se avviene un errore a livello di servlet
     * @throws IOException se avviene un errore I/O
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            wishlister.WLWebServiceService service = new wishlister.WLWebServiceService();
            wishlister.WLWebService port = service.getWLWebServicePort();
            String result = port.listaRegali(Long.valueOf(request.getAttribute("uid").toString()));

            //////////////////////////////////////

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(result));
            Document doc = db.parse(inStream);

            doc.getDocumentElement().normalize();
            //out.println("Root element " + doc.getDocumentElement().getNodeName());
            NodeList nodeLst = doc.getElementsByTagName("regalo");
            //out.println("Informazioni sugli utenti:");
            ArrayList<Prodotto> listaRegali = new ArrayList<Prodotto>();

            for (int s = 0; s < nodeLst.getLength(); s++) {

                Node fstNode = nodeLst.item(s);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element fstElmnt = (Element) fstNode;

                    NodeList ridElmntLst = fstElmnt.getElementsByTagName("id");
                    Element ridElmnt = (Element) ridElmntLst.item(0);
                    NodeList ridNode = ridElmnt.getChildNodes();
                    Long rid = Long.valueOf(((Node) ridNode.item(0)).getNodeValue());

                    NodeList nomeElmntLst = fstElmnt.getElementsByTagName("nome");
                    Element nomeElmnt = (Element) nomeElmntLst.item(0);
                    NodeList nomeNode = nomeElmnt.getChildNodes();
                    String nome = ((Node) nomeNode.item(0)).getNodeValue();

                    NodeList tipoElmntLst = fstElmnt.getElementsByTagName("tipo");
                    Element tipoElmnt = (Element) tipoElmntLst.item(0);
                    NodeList tipoNode = tipoElmnt.getChildNodes();
                    String tipo = ((Node) tipoNode.item(0)).getNodeValue();

                    NodeList descElmntLst = fstElmnt.getElementsByTagName("descrizione");
                    Element descElmnt = (Element) descElmntLst.item(0);
                    NodeList descNode = descElmnt.getChildNodes();
                    String descrizione = ((Node) descNode.item(0)).getNodeValue();

                    Prodotto p = new Prodotto();
                    p.setId(rid);
                    p.setNome(nome);
                    p.setCodice(tipo);
                    p.setDescrizione(descrizione);
                    listaRegali.add(p);
                }
                request.setAttribute("lista", listaRegali);
                request.setAttribute("utente", request.getAttribute("utente"));
                request.setAttribute("username", request.getAttribute("username"));

            }

            //////////////////////////////////////

        } catch (Exception e) {
            //e.printStackTrace(out);
            request.setAttribute("err", "Errore: impossibile recuperare la lista di regali da WishLister.");
        } finally {
            //out.close();
            RequestDispatcher rq = request.getRequestDispatcher("/regali.jsp");
            rq.forward(request, response);
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>
}
